package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.common.Result;
import com.example.common.ResultStatus;
import com.example.pojo.User;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@CrossOrigin
@RequestMapping("/user")
@Slf4j
public class UserController {
    UserService userService;


    @Autowired
    UserController(UserService userService) {
        this.userService = userService;
    }


    @PostMapping("/register")
    public String register(@RequestBody JSONObject json) {
        log.info("res:{}",json);
        try{
            //     if ((int)userService.addUser(json)==0){
            //        return  ResultStatus.USER_MOBILE.toString();
            //  }
            userService.addUser(json);
        }catch (Exception e){
            return ResultStatus.USER_EXIST.toString();
        }

        return ResultStatus.SUCCESS.toString();
    }


    @PostMapping("/login")
    public String login(HttpServletResponse resp, @RequestBody JSONObject json) {
        User user = (User) userService.login(json);
        //log.info("res:{}",json);
        if (user != null) {
            Cookie cookie = new Cookie("user",user.getUserId().toString());
            resp.addCookie(cookie);
            if(user.getStatus()==0){
                if (user.getAdmin() == 1) {
                    return new Result<>(ResultStatus.AD_SUCCESS,user).toJson();
                }else
                    return new Result<>(ResultStatus.SUCCESS,user).toJson();
            } else
                return  ResultStatus.USER_LOCK.toString();

        }
        return ResultStatus.ERROR.toString();
    }

    @PostMapping("/find")
    public String find(@RequestBody JSONObject json){
        try{
            userService.find(json);
        }catch (Exception  e){
            return ResultStatus.ERROR.toString();
        }
        return ResultStatus.SUCCESS.toString();
    }





    @PostMapping("/update")
    public String update(@RequestBody JSONObject json, HttpServletRequest req) {
        User user= (User) userService.getUser(req);
        userService.update(json, user);
        return ResultStatus.SUCCESS.toString();
    }
}
